package contact

import (
	"context"
	"git.mycaigou.com/gfyx/common/tenant_db"
	"git.myscrm.cn/golang/common/uuid"
	"gorm.io/gorm"
	"time"
)

type GfyxOpTelViewHistoryRepos struct {
	tenant_db.TenantDB
}

func NewOpTelViewHistoryRepos() GfyxOpTelViewHistoryReposIface {
	return &GfyxOpTelViewHistoryRepos{}
}

func (g *GfyxOpTelViewHistoryRepos) SaveOpTelViewHistory(ctx context.Context, data *GfyxOpTelViewHistory) error {
	data.OpTelViewHistoryGUID = uuid.GetUUID()
	data.CreatedTime = time.Now()
	data.ModifiedTime = time.Now()
	err := g.GetTenantDB(ctx).Create(data).Error
	if err != nil {
		return err
	}
	return nil
}

func (g *GfyxOpTelViewHistoryRepos) GetOpTelViewHistory(ctx context.Context, telNumber string, createGUID string) (*GfyxOpTelViewHistory, error) {
	gfyxOpTelViewHistory := &GfyxOpTelViewHistory{}
	db := g.GetTenantDB(ctx).
		Where("TelNumber = ?", telNumber).
		Where("CreatedGUID = ?", createGUID).
		Order("CreatedTime desc").
		Limit(1)

	err := db.Find(&gfyxOpTelViewHistory).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return gfyxOpTelViewHistory, err
	}
	return gfyxOpTelViewHistory, nil
}

func (g *GfyxOpTelViewHistoryRepos) GetOpTelViewHistoryBatch(ctx context.Context, telNumber []string, createdGUID string) (map[string]int32, error) {
	resp := map[string]int32{}
	if len(telNumber) <= 0 {
		return resp, nil
	}
	gfyxOpTelViewHistory := make([]*GfyxOpTelViewHistory, 0)
	db := g.GetTenantDB(ctx).
		Where("TelNumber in (?)", telNumber).
		Where("CreatedGUID =?", createdGUID).
		Order("CreatedTime desc")

	err := db.Find(&gfyxOpTelViewHistory).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return resp, nil
		}
		return nil, err
	}
	for _, v := range telNumber {
		for _, item := range gfyxOpTelViewHistory {
			if v == item.TelNumber {
				resp[v] = item.ViewTimes
			}
		}
	}
	return resp, nil
}

func (g *GfyxOpTelViewHistoryRepos) UpdateViewTimes(ctx context.Context, telNumber string, createdGUID string) (bool, error) {
	g.GetTenantDB(ctx).Exec("UPDATE `gfyx_optelviewhistory` SET ViewTimes=ViewTimes+1 where `TelNumber`=? and CreatedGUID=?", telNumber, createdGUID)
	return true, nil
}

func (g *GfyxOpTelViewHistoryRepos) GetCurrentMonthViewTimes(ctx context.Context, createGUID string, monthStart string, monthEnd string) (int64, error) {
	var total int64
	err := g.GetTenantDB(ctx).Table(GfyxOpTelViewHistory{}.TableName()).Where("CreatedGUID = ? and VersionNumber >= ? and VersionNumber < ?",
		createGUID, monthStart, monthEnd).Count(&total).Error
	if err != nil {
		return 0, err
	}
	return total, nil
}
